import axios from 'axios'
axios.defaults.timeout = 5000; //响应时间
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'; //配置请求头
//POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
  //在发送请求之前做某件事
  // if (config.method === 'post') {
  //   config.data = qs.stringify(config.data);
  // }
  return config;
}, (error) => {
  console.log('错误的传参');
  return Promise.reject(error);
});

//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) => {
  //对响应数据做些事
  console.log(res, '对响应数据做些事')
  if (res.data.code == 400) {
    return Promise.reject(res);
  }
  return res;
}, (error) => {
  console.log('网络异常')
  return Promise.reject(error);
});

//返回一个Promise(发送post请求)
export function Post(url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(response => {
        console.log(response)
        resolve(response.data);
      }, err => {
        reject(err);
      })
      .catch((error) => {
        reject(error)
      })
  })
}
////返回一个Promise(发送get请求)
export function Get(url, param) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params: param })
      .then(response => {
        console.log(response)
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export function Put(url, param) {

  return new Promise((resolve, reject) => {
    console.log(param, 111111111111111111)
    axios.put(url, param)
      .then(response => {
        console.log(response)
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
export function Delete(url, param) {
  return new Promise((resolve, reject) => {
    axios.delete(url, { params: param })
      .then(response => {
        console.log(response)
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
export default {
  Post,
  Get,
  Put,
  Delete
}
